package com.xyhuo.leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class IsHappy {

    Set<Integer> set = new HashSet<>();

    public boolean isHappy(int n) {
        if (set.contains(n)) {
            return false;
        }
        set.add(n);
        List<Integer> list = new ArrayList<>();
        while (n > 9) {
            int tmp = n - 10 * (n / 10);
            if (tmp != 0) {
                list.add(tmp);
            }
            n = n / 10;
        }
        list.add(n);

        int result = 0;
        for (Integer num : list) {
            result += Math.pow(num, 2);
        }

        if (result == 1) {
            return true;
        } else {
            return isHappy(result);
        }
    }

    public static void main(String[] args) {
        IsHappy i = new IsHappy();
        i.isHappy(19);
    }
}
